package com.netease.financial.module.asset;

import com.netease.financial.common.util.preferences.BadgePreferencesHelper;
import com.netease.financial.domain.interactor.DefaultSubscriber;
import com.netease.financial.domain.interactor.UseCase;
import com.netease.financial.domain.model.UnreadMessageCount;
import com.netease.financial.internal.di.ActivityScope;
import com.netease.financial.mapper.NfsViewModelDataMapper;
import com.netease.financial.viewmodel.UnreadMessageCountViewModel;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created by wyf on 10/19/15.
 */
@ActivityScope
public class AssetPresenterImpl implements AssetPresenter {

    private AssetView assetView;

    private final UseCase getUnreadSiteMessageCount;
    private final NfsViewModelDataMapper nfsViewModelDataMapper;

    @Inject
    public AssetPresenterImpl(@Named("unread_site_message_count") UseCase getUnreadSiteMessageCount, NfsViewModelDataMapper nfsViewModelDataMapper) {
        this.getUnreadSiteMessageCount = getUnreadSiteMessageCount;
        this.nfsViewModelDataMapper = nfsViewModelDataMapper;
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onDestroy() {
        getUnreadSiteMessageCount.unsubscribe();
    }

    @Override
    public void setView(AssetView view) {
        this.assetView = view;
    }

    @Override
    public void initialize() {

    }

    private void onUnreadMessageCountReceived(UnreadMessageCount model) {
        final UnreadMessageCountViewModel viewModel = nfsViewModelDataMapper.transform(model);
        BadgePreferencesHelper.setUnreadPrivateMessageCount(viewModel.getCount());
        this.assetView.showTabBadgeIfNeed();
    }

    @Override
    public void checkUnreadSiteMessageCount() {
        this.getUnreadSiteMessageCount.execute(new UnreadSiteMessageCountSubscriber());
    }

    @Override
    public void changeTabBadgeNumber(int badge) {
        BadgePreferencesHelper.setUnreadPrivateMessageCount(badge);
        this.assetView.showTabBadgeIfNeed();
    }

    private final class UnreadSiteMessageCountSubscriber extends DefaultSubscriber<UnreadMessageCount> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            BadgePreferencesHelper.setUnreadPrivateMessageCount(0);
//            assetView.showTabBadgeIfNeed();
            e.printStackTrace();
        }

        @Override
        public void onNext(UnreadMessageCount model) {
            AssetPresenterImpl.this.onUnreadMessageCountReceived(model);
        }
    }

}
